package com.work.mvc.view.table;

import java.util.*;

import com.vaadin.data.Property;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.ui.Table;
import com.work.constants.view.ComponentsSize;
import com.work.mvc.controler.WorkTimeUtils;
import com.work.mvc.model.pojo.*;
import com.work.mvc.view.TablePropertyFormat;
import com.work.mvc.view.table.property.SummaryWorkTimeProperty;

public class SummaryWorkTimeTableView extends Table{
	
	private static final long serialVersionUID = 276175592136878736L;
	
	private Map<Integer, MonthSummary> summaries;
	private YearSummary yearSummary;
	
	public SummaryWorkTimeTableView(Map<Integer, MonthSummary> summaries) {
		this.summaries = summaries;
		this.yearSummary = new YearSummary();
		WorkTimeUtils.calculateYearSummary(summaries, yearSummary);
		
		init();
	}
	
	private void init()
	{
		List<MonthSummary> monthSummaries = new ArrayList<MonthSummary>();
		for (Map.Entry<Integer, MonthSummary> entry : summaries.entrySet()) {
			monthSummaries.add(entry.getValue());
		}
		
		IndexedContainer container = TableContentFactory.getInstance().createTableContent(TablePropertyLists.summarizeWorkTimeTable, monthSummaries);
		this.setCellStyleGenerator(new Table.CellStyleGenerator()
		{
			private static final long serialVersionUID = -1857856049625754877L;

			@Override
			public String getStyle(Table source, Object itemId, Object propertyId)
			{
				String style = TableStyles.getSummaryWorkTimeCellStyle(source, itemId, propertyId);
				if (style != null) {
					return style;
				}
				
				return "white";
			}
		});
		
		this.setWidth(ComponentsSize.FULL);
		int height = (ComponentsSize.TABLE_HEADER_HEIGHT_INT+(ComponentsSize.SUMMARY_TABLE_ROW_HEIGHT_INT*summaries.size()) + 40);
		this.setHeight(height + "px");
		this.setContainerDataSource(container);
		this.setFooterVisible(true);
		this.setImmediate(true);

		for (SummaryWorkTimeProperty property : TablePropertyLists.summarizeWorkTimeTable) {
			this.setColumnHeader(property, property.getName());
			this.setColumnWidth(property, property.getWidth());
			
			String summaryValue = property.getYearSummaryValue(yearSummary);
			this.setColumnFooter(property, summaryValue);
		}
	}
	
	@Override
	protected String formatPropertyValue(Object rowId, Object colId, Property<?> property)
	{
		String formattedValue = TablePropertyFormat.formatSummaryWorktimePropertyValue(rowId, colId, property);
		if (formattedValue != null) {
			return formattedValue;
		}

		return super.formatPropertyValue(rowId, colId, property);
	}
}
